import 'dart:convert';
import 'dart:io';

import 'package:cave_flutter/widgets/nine_grid_view/drag_widgets/whl_drag_gesture_page_route.dart';
import 'package:cave_flutter/widgets/nine_grid_view/whl_image_browser_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import '../../../../common/chat_manager.dart';
import '../../../../widgets/brick/brick.dart';
import '../whl_chat_room_logic.dart';

double kFAMsgImageDefaultWidth = 158.w;
double kFAMsgImageMinWidth = 50.w;
double kFAMsgImageMaxWidth = 158.w;
double kFAMsgImageMaxHeight = 260.h;

class WhlImageMessageItem extends StatelessWidget {
  const WhlImageMessageItem({super.key, required this.message});

  final NIMMessage message;

  @override
  Widget build(BuildContext context) {
    bool isSend = message.messageDirection == NIMMessageDirection.outgoing;
    Map dic = message.messageAttachment?.toMap() ?? {};
    print("load 111111");
    print(dic);
    String path = dic["path"] ?? "";
    String thumbUrl = dic["thumbUrl"] ?? "";
    Size imageSzie = formatImageSize(dic["w"] ?? 0, dic["h"] ?? 0);
    return Hero(
      tag: message.uuid ?? '',
      child: path?.isNotEmpty ?? false
          ? UIImage(
              margin: EdgeInsets.only(bottom: 10.h),
              image: Image.file(File(path ?? ''), fit: BoxFit.fitWidth),
              width: imageSzie.width,
              height: imageSzie.height,
              radius: 12.w,
              clipBehavior: Clip.hardEdge,
              onTap: () {
                doClickImage();
              },
            )
          : UIImage(
              margin: EdgeInsets.only(bottom: 10.h),
              httpImage: thumbUrl,
              fit: BoxFit.fitWidth,
              // image: Image.memory(
              //   base64.decode(message.thumbnailBase64String?.replaceAll(RegExp(r'\s+'), '') ?? ''),
              //   fit: BoxFit.fitWidth,
              // ),
              width: imageSzie.width,
              height: imageSzie.height,
              radius: 12.w,
              clipBehavior: Clip.hardEdge,
              onTap: () {
                doClickImage();
              },
            ),
    );
  }

  Size formatImageSize(num width, num height) {
    double resultWidth = width.toDouble();
    double resultHeight = height.toDouble();
    if (width == 0 && height == 0) {
      resultWidth = kFAMsgImageMaxWidth;
      resultHeight = kFAMsgImageDefaultWidth;
    } else {
      double tmpWidth = width.toDouble();
      if (width < kFAMsgImageMinWidth) {
        tmpWidth = kFAMsgImageMinWidth;
      }
      if (width > kFAMsgImageMaxWidth) {
        tmpWidth = kFAMsgImageMaxWidth;
      }
      double tmpHeight = tmpWidth / width * height;
      if (tmpHeight > kFAMsgImageMaxHeight) {
        tmpHeight = kFAMsgImageMaxHeight;
      }
      resultWidth = tmpWidth;
      resultHeight = tmpHeight;
    }
    return Size(resultWidth, resultHeight);
  }

  doClickImage() {
    WhlChatRoomLogic logic = Get.find();
    List allList = logic.messageList;
    List imageList = allList
        .where((element) {
          NIMMessage msg = element;
          if (msg.messageType == NIMMessageType.image) {
            return true;
          }
          return false;
        })
        .toList()
        .reversed
        .toList();
    int selectedIndex = 0;
    List<String> msgIds = [];
    imageList.forEach((element) {
      NIMMessage msg = element;
      msgIds.add(msg.uuid ?? "");
      if (msg.uuid == message.uuid) {
        selectedIndex = imageList.indexOf(element);
      }
    });
    Navigator.push(
      Get.context!,
      WhlDragGesturePageRoute(
        builder: (context) {
          return WhlImageBrowserPage(
            tags: msgIds,
            messageList: imageList.map((e) {
              NIMMessage imageMessage = e;
              return imageMessage;
            }).toList(),
            index: selectedIndex,
          );
        },
      ),
    );
  }
}
